package com.finalist.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * 通过文件名读取磁盘文件在页面显示servlet
 * 
 * @author 
 * 
 *         <pre>
 *     通过<code>fileName</code>读取磁盘图片
 * </pre>
 */
public class ShowPicServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger logger = Logger.getLogger(ShowPicServlet.class);

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ShowPicServlet() {
		super();
	}

	/**
	 * 主体逻辑处理
	 * 
	 * @author 
	 * 
	 *         <pre>
	 *   通过<code>fileName</code>获取磁盘文件，响应与页面
	 * </pre>
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String filePath = request.getParameter("filePath");// 获取图片名字

		OutputStream os = response.getOutputStream();
		File file = new File(filePath);
		FileInputStream fips = null;
		try {
			fips = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			logger.error("", e);
		}
		if (fips != null) {
			byte[] btImg = readStream(fips);
			try {
				os.write(btImg);
			} catch (NullPointerException e) {
				logger.error("", e);
			}
		}

		os.flush();
	}

	/**
	 * 读取管道中的流数据
	 * 
	 * @author 
	 */
	public byte[] readStream(InputStream inStream) {
		ByteArrayOutputStream bops = new ByteArrayOutputStream();
		int data = -1;
		try {
			while ((data = inStream.read()) != -1) {
				bops.write(data);
			}
			return bops.toByteArray();
		} catch (Exception e) {
			logger.error("", e);
			return null;
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
